<template>
  <div>
    <div class="search-bar run-search-bar" style="background:none;">
      <div style="margin: 15px 20px 0;">
        <div class="rp-handle-bar" v-if="formButtons.length > 0 && searchFields.length > 0" slot="handle-bar">
          <Button
            v-for="btn in formButtons"
            :key="btn.optType"
            @click.native="getClickEvent(btn)"
            :type="btn.optType == 'search' ? 'warning' : 'info'"
            :icon="btn.optType == 'search' ? 'search' : 'loop'"
            
            style="margin-left:5px;"
            >{{ btn.optType == "search" ? "查询" : "重置" }}</Button
          >
        </div>
      </div>
      <div>
        <Form
          :model="searchForm"
          :rules="ruleValidate"
          ref="searchForm"
          slot="search-bar"
          label-position="right"
          style="padding: 10px 20px;min-height: 50px;text-align:left;"
          inline
          v-if="searchFields.length > 0"
        >
          <Form-item v-for="item in searchFields" :key="item.paramsName" :label="item.label" v-show="item.display">
            <Input
              v-if="item.formElement == 'INPUT'"
              type="text"
              v-model="searchForm[item.paramsName]"
              :placeholder="item.placeholder || '请输入'"
              :size="item.size || 'small'"
              :style="`width:${item.width}px`"
              :maxlength="item.maxlength || 30"
              :number="item.numberInput || false"
            ></Input>
            <Select
              v-if="item.formElement == 'SELECT'"
              v-model="searchForm[item.paramsName]"
              :placeholder="item.placeholder || '请选择'"
              :size="item.size || 'small'"
              :style="`width:${item.width}px`"
              :multiple="item.multiple || false"
              :filterable="item.filterable || false"
            >
              <Option v-for="i in item.content" :key="i.key" :value="i.key">{{ i.name }}</Option>
            </Select>
            <DatePicker
              v-if="item.formElement == 'DATE'"
              v-model="searchForm[item.paramsName]"
              :placeholder="item.placeholder || '请选择'"
              :size="item.size || 'small'"
              :style="`width:${item.width}px`"
              :type="item.datePickerType || 'date'"
            ></DatePicker>
            <TimePicker
              v-if="item.formElement == 'TIME'"
              v-model="searchForm[item.paramsName]"
              :placeholder="item.placeholder || '请选择'"
              :size="item.size || 'small'"
              :style="`width:${item.width}px`"
              :type="item.timePickerType || 'time'"
            ></TimePicker>
            <CheckboxGroup
              v-if="item.formElement == 'CHECKBOX'"
              v-model="searchForm[item.paramsName]"
              :size="item.size || 'small'"
            >
              <Checkbox v-for="j in item.content" :key="j.key" :label="j.key">{{ j.name }}</Checkbox>
            </CheckboxGroup>
            <RadioGroup
              v-if="item.formElement == 'RADIO'"
              v-model="searchForm[item.paramsName]"
              :size="item.size || 'small'"
            >
              <Radio v-for="j in item.content" :key="j.key" :label="j.key">{{ j.name }}</Radio>
            </RadioGroup>
          </Form-item>
        </Form>
      </div>
    </div>
    <div class="selection-area" v-if="hasSelectionArea && selectionAreaItem && allSelection.length > 0">
      <Tag
        v-for="item in allSelection"
        :key="item[selectionAreaItem.key]"
        :name="item[selectionAreaItem.key]"
        closable
        @on-close="closeTag"
        >{{ item[selectionAreaItem.title] }}</Tag
      >
    </div>
    <div class="single-table-con">
      <div class="table-bar" style="text-align:left; margin-bottom: 10px;">
        <RPButton
          v-for="(btn, index) in tableButtons"
          :key="index"
          :text="btn.name"
          @click.native="btn.handle"
          :type="btn.type || 'default'"
          :size="btn.size || 'default'"
          :disabled="btn.disabled || false"
          :shape="btn.shape || undefined"
          style="margin-right:18px"
          >{{ btn.name }}</RPButton
        >
      </div>
      <Table
        
        ref="table"
        :loading="loading"
        @on-current-change="onCurrentChange"
        :highlight-row="highlightRow"
        :data="tableData"
        :columns="tableColumns"
        @on-selection-change="selectionChange"
        @on-sort-change="sortHandle"
        @on-row-click="rowClickHandle"
        stripe
      ></Table>
      <div style="margin: 10px;overflow: hidden" v-if="isPage">
        <div style="float: right;">
          <Page
            :placement="placement"
            :total="total"
            :show-total="showTotal"
            :page-size-opts="pageSizeOpts"
            :show-sizer="showSizer"
            :page-size="pageSize"
            :current="currentPage"
            @on-change="changePage"
            size="small"
            :transfer="true"
            @on-page-size-change="changePageSize"
          ></Page>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
const startPage = 1;
export default {
  name: "PageTableContent",
  components: {},
  props: {
    config: {
      type: Object,
      default: {}
    }
  },
  data() {
    //init searchForm
    let allData = {
      searchForm: {},
      ruleValidate: {},
      formatSearchFields: [],
      ...this.config
    };
    if (!this.config.searchFields) {
      allData.searchFields = [];
    }
    if (!this.config.tableButtons) {
      allData.tableButtons = [];
    }
    if (!this.config.formButtons) {
      allData.formButtons = [];
    }
    if (this.config.searchFields) {
      for (let item of this.config.searchFields) {
        allData.searchForm[item.paramsName] = undefined;
      }
      let formatSearchFields = this.config.searchFields;
      formatSearchFields.sort((a, b) => {
        return a.searchSort - b.searchSort;
      });
      allData.formatSearchFields = [].concat(formatSearchFields);
    }
    return {
      tableData: [],
      tableColumns: [],
      total: 0,
      hasSelectionArea: false,
      // currentPage: 1,
      selection: [],
      allSelection: [],
      loading: false,
      param: {
        tenantCode: $store.state["ripples-components"].userInfo.tenantCode,
        commonPageDTO: {
          //currentPage: 1,
          // pageSize: 10
        },
        sortDTO: {
          fieldName: "",
          orderBy: ""
        },
        condition: {}
      },
      selectionAreaItem: { key: "id", title: "configName" },
      messageJob: undefined,
      isSelectionChange: false,
      currentRow: undefined,
      pageSize: 0,
      ...allData
    };
  },
  computed: {
    placement() {
      let pageTotal = 0;
      if (this.total % this.pageSize == 0) {
        pageTotal = this.total / this.pageSize;
      } else {
        pageTotal = this.total / this.pageSize + 1;
      }
      pageTotal = parseInt(pageTotal);
      return this.total % this.pageSize < 3 && this.currentPage == pageTotal ? "bottom" : "top";
    },
    lang() {
      let _store = this.$store || window.$store;
      return _store && _store.state && _store.state.lang;
    }
  },
  created: function() {
    this.dataCompatibilityProcess();
    this.getColumns();
    for (let c of this.tableColumns) {
      if (!~"selection".indexOf(c.type)) {
        // c.ellipsis = true;
        // 无render函数的统一添加字段过长的title提示
        this.initTableEllipsisColumn(c);
      }
    }
  },
  beforeMount: function() {},
  mounted: function() {
    // this.autoFirst && this.load(startPage);
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    // 数据兼容性处理, 苦逼的事
    dataCompatibilityProcess() {
      this.setCurrentPage(this.currentPage || this.param.commonPageDTO.currentPage);

      this.setPageSize(this.pageSize || this.param.pageSize || this.param.commonPageDTO.pageSize);
    },
    setCurrentPage(newValue) {
      this.currentPage = this.param.pageNum = this.param.commonPageDTO.currentPage = newValue || 1;
    },
    setPageSize(newValue) {
      this.pageSize = this.param.pageSize = this.param.commonPageDTO.pageSize = newValue || 10;
    },
    setTotal(newValue) {
      this.param.commonPageDTO.recordCount = this.total = newValue;
    },
    initTableEllipsisColumn(columnItem) {
      this.$set(columnItem, "ellipsis", true);
      if (!columnItem.render) {
        this.$set(columnItem, "render", (h, params) => {
          return h("span", { attrs: { title: params.row[params.column.key] } }, params.row[params.column.key]);
        });
      }
    },
    onCurrentChange(currentRow, oldCurrentRow) {
      this.currentRow = Object.assign({}, currentRow);
    },
    getHighlightRow() {
      return this.currentRow;
    },
    getColumns() {
      if (typeof this.columnsFn == "function") {
        this.tableColumns = [].concat(this.columnsFn());
      } else {
        let formatColumns = this.columns;
        formatColumns.sort((a, b) => {
          return a.headerSort - b.headerSort;
        });
        this.tableColumns = [].concat(formatColumns);
      }
    },
    refresh() {
      this.setCurrentPage(1);
      this.$nextTick(() => {
        this.load();
      });
    },
    // tableClickEvent(btn) {
    //   this.$emit(btn.handle);
    // },
    getClickEvent(btn) {
      return btn.optType === "search" ? this.search() : this.reset();
    },
    resetFields() {
      for (let item of this.searchFields) {
        this.searchForm[item.paramsName] = undefined;
      }
    },
    search(page) {
      this.load(this.searchForm, page || startPage);
    },
    reset() {
      this.resetFields();
      this.search(startPage); //请求第一页
    },
    load(param = {}, page) {
      this.selection = [];
      // for (let p in param) {
      //   this.param[p] = param[p];
      // }
      this.param = {
        ...this.param,
        condition: {
          ...param
        },
        ...param
      };

      this.loading = true;
      if (!!page && typeof page == "number") {
        this.setCurrentPage(page);
      }

      this.runLoadProcess();
    },
    runLoadProcess(initParam) {
      if (typeof this.loadDataFn === "function") {
        this.loadDataFn(this);
      } else if (this.action) {
        this.loadAjax(initParam);
      } else {
        this.loadLocal();
      }
    },
    loadLocal() {
      if (!this.isPage) {
        this.$nextTick(() => {
          this.tableData = [].concat(this.resource);
          this.loading = false;
        });
        return;
      }

      this.setTotal(this.resource.length);
      let start = (this.currentPage - 1) * this.pageSize;

      let end = start + this.pageSize;
      end = this.resource.length > end ? end : this.resource.length;
      this.tableData = [];
      for (let i = start; i < end; i++) {
        this.tableData.push(this.resource[i]);
      }
      this.$nextTick(() => {
        this.loading = false;
      });
    },
    responseProcess(res) {
      this.loading = false;
      if (!res) return;
      if (this.customDataProcess) {
        this.customDataProcess(this, res);
        return;
      }

      this.setCurrentPage(res.currentPage || res.pageNum || 1);
      this.setTotal(res.recordCount || res.total || 0);
      this.tableData = [];
      for (let item of res.recordList || res.records || []) {
        this.tableData.push(item);
      }
    },
    loadAjax() {
      const _store = window.$store || this.$store;
      _store && _store.dispatch && _store.dispatch(this.action, this.param).then(this.responseProcess);
    },
    changePage(page) {
      this.setCurrentPage(page);
      this.load();
      this.checkedRow();
    },
    changePageSize(page) {
      this.setPageSize(page);
      this.load();
      this.checkedRow();
    },
    selectionChange(selection) {
      // 更新标签栏
      this.updateAllSelection(selection);
      this.isSelectionChange = true;
      this.selection = selection;
      if (typeof this.onSelectionChange == "function") {
        this.onSelectionChange(selection);
      }
    },
    getSelectioned() {
      return this.isSelectionChange ? this.selection : undefined;
    },
    sortHandle(obj) {
      this.param.sortDTO.fieldName = obj.key;
      this.param.sortDTO.orderBy = obj.order;
      if (this.param.sortDTO.orderBy == "normal") {
        this.param.sortDTO = {
          fieldName: "",
          orderBy: ""
        };
      }

      if (obj.order == "desc") {
        this.param.descs = [obj.key];
        this.param.ascs = [];
      } else if (obj.order == "asc") {
        this.param.ascs = [obj.key];
        this.param.descs = [];
      } else {
        this.param.ascs = [];
        this.param.descs = [];
      }

      this.refresh();
    },
    getSortData() {
      return this.param.sortDTO;
    },
    getTableObj() {
      return this.$refs["table"];
    },
    closeTag(event, name) {
      // 唯一标识
      let key;
      if (this.selectionAreaItem && this.selectionAreaItem.key) {
        key = this.selectionAreaItem.key;
      } else {
        return;
      }
      // 更新标签栏
      for (let index = 0; index < this.allSelection.length; index++) {
        const item = this.allSelection[index];
        if (name == item[key]) {
          this.allSelection.splice(index, 1);
          break;
        }
      }
      // 更新表格
      for (let i = 0; i < this.tableData.length; i++) {
        let row = this.tableData[i];
        if (name == row[key]) {
          row._checked = false;
        } else {
          row._checked = false;
          for (let j = 0; j < this.selection.length; j++) {
            const checkedRow = this.selection[j];
            if (row[key] == checkedRow[key]) {
              row._checked = true;
              break;
            }
          }
        }
      }
      // 更新已选择
      for (let index = 0; index < this.selection.length; index++) {
        const item = this.selection[index];
        if (name == item[key]) {
          this.selection.splice(index, 1);
          break;
        }
      }
      this.tableData = this.tableData.concat([]);
    },
    // 更新标签栏
    updateAllSelection(newSelection) {
      // 唯一标识
      let key;
      if (this.selectionAreaItem && this.selectionAreaItem.key) {
        key = this.selectionAreaItem.key;
      } else {
        return;
      }
      // 新增的选项
      // 本页新增 = 本页已选New - 本页已选Old
      let increasedData = newSelection.filter(newData => {
        for (let index = 0; index < this.selection.length; index++) {
          const oldData = this.selection[index];
          if (oldData[key] == newData[key]) {
            return false;
          }
        }
        return true;
      });
      // 减少的选项
      // 本页减少 = 本页已选Old - 本页已选New
      let reducedData = this.selection.filter(oldData => {
        for (let index = 0; index < newSelection.length; index++) {
          const newData = newSelection[index];
          if (oldData[key] == newData[key]) {
            return false;
          }
        }
        return true;
      });
      // 标签栏 = 标签栏 + 本页新增 - 本页减少
      reducedData.forEach(reduced => {
        for (let index = 0; index < this.allSelection.length; index++) {
          const selectionData = this.allSelection[index];
          if (selectionData[key] == reduced[key]) {
            this.allSelection.splice(index, 1);
            return;
          }
        }
      });
      this.allSelection = this.allSelection.concat(increasedData);
    },
    // 回显已勾选项
    checkedRow() {
      // 唯一标识
      let key;
      if (this.selectionAreaItem && this.selectionAreaItem.key) {
        key = this.selectionAreaItem.key;
      } else {
        return;
      }
      this.tableData.forEach(row => {
        for (let index = 0; index < this.allSelection.length; index++) {
          const element = this.allSelection[index];
          if (row[key] == element[key]) {
            row._checked = true;
            this.selection.push(element);
            return;
          }
        }
        row._checked = false;
      });
    }
  },
  watch: {
    lang() {
      this.getColumns();
    }
    // resource(newVal, oldVal) {
    //   this.resource = newVal;
    // }
  },
  directives: {}
};
</script>
<style scoped>
</style>
